package cn.ibizlab.util.adapter.service.impl;

import cn.ibizlab.util.adapter.service.SysRuntimeModelService;
import net.ibizsys.central.database.SysDBSchemeRuntime;
import net.ibizsys.central.dataentity.IDataEntityRuntime;
import net.ibizsys.central.util.ISearchContext;
import net.ibizsys.model.dataentity.ds.IPSDEDataQuery;
import net.ibizsys.model.dataentity.ds.IPSDEDataSet;
import org.springframework.data.domain.Page;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *  adapter 数据库运行时对象，用于执行处理逻辑中的sql调用处理
 */
public class DefaultAdapterDBSchemeRuntime extends SysDBSchemeRuntime {

    private String regex = "\\?";
    private Pattern pattern = Pattern.compile(regex);

    /**
     * 执行sql
     * @param strSQL
     * @param params
     * @return
     * @throws Throwable
     */
    @Override
    public int executeSQL(String strSQL, List<Object> params) throws Throwable {

        Matcher m = pattern.matcher(strSQL);
        int i = 0;
        while (m.find()) {
            strSQL = strSQL.replaceFirst(regex, String.format("#{et.%s}", i));
            i++;
        }
        return SysRuntimeModelService.getSysRuntimeAdapterService().executeSQLReal(strSQL, convertListParam(params));
    }

    /**
     * list条件转换
     *
     * @param params
     * @return
     */
    private Map<String, Object> convertListParam(List<Object> params) {
        Map<String, Object> mapParams = new HashMap<>();
        if (params != null) {
            for (int i = 0; i < params.size(); i++) {
                mapParams.put(String.valueOf(i), params.get(i));
            }
        }
        return mapParams;
    }

    /**
     * 实体数据查询
     *
     * @param dataEntityRuntime 实体运行时对象
     * @param dataSet           数据集合
     * @param searchContext     查询上下文条件
     * @param outputFields
     * @param extParamMap
     * @return
     * @throws Throwable
     */
    @Override
    public Page fetchDataSet(IDataEntityRuntime dataEntityRuntime, IPSDEDataSet dataSet, ISearchContext searchContext, String[] outputFields, Map<String, Object> extParamMap) throws Throwable {
        return SysRuntimeModelService.getSysRuntimeAdapterService().fetchDataSetReal(dataEntityRuntime, dataSet, searchContext);
    }

    /**
     * 实体数据查询
     */
    @Override
    public List query(IDataEntityRuntime iDataEntityRuntime, IPSDEDataQuery iPSDEDataQuery, ISearchContext iSearchContext, String[] outputFields, Map<String, Object> extParamMap) throws Throwable {
        return SysRuntimeModelService.getSysRuntimeAdapterService().fetchDataSetReal(iDataEntityRuntime, iPSDEDataQuery, iSearchContext);
    }
}
